package nl.hva.three2learn.dao;

import java.util.List;

import nl.hva.three2learn.model.Course;
import nl.hva.three2learn.model.Payment;
import nl.hva.three2learn.model.User;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class PaymentDaoImpl implements PaymentDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public List<Payment> findPaymentsFor(User user) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Payment p where p.user = :user");
		q.setEntity("user", user);		
		
		List<Payment> payments = q.list();
		
		session.getTransaction().commit();
		
		return payments;
	}
	
	@Override
	public List<Payment> findPaymentsFor(User user, Course course) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Payment p where p.user.id = :user and p.period.course = :course");
		q.setEntity("user", user);		
		q.setEntity("course", course);
		
		List<Payment> payments = q.list();
		
		session.getTransaction().commit();
		
		return payments;
	}
	
	@Override
	public void save(Payment payment) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(payment);
		session.getTransaction().commit();
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
